package org.ngmj.client.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.concurrent.Promise;
import lombok.extern.slf4j.Slf4j;
import org.ngmj.message.RpcResponseMessage;

import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@ChannelHandler.Sharable
public class RpcResponseMessageHandler extends SimpleChannelInboundHandler<RpcResponseMessage> {

    public static ConcurrentHashMap<Integer, Promise<Object>> PROMISES_MAP = new ConcurrentHashMap<>();

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, RpcResponseMessage rpcResponseMessage) throws Exception {
        log.info("收到服务端的响应：{}", rpcResponseMessage);
        Promise<Object> promise = PROMISES_MAP.remove(rpcResponseMessage.getSequenceId());
        if (promise != null) {
            if (rpcResponseMessage.getExceptionValue() != null) {
                promise.setFailure(rpcResponseMessage.getExceptionValue());
            } else {
                promise.setSuccess(rpcResponseMessage.getReturnValue());
            }
        }
    }
}
